<template>
  <PublicLoading v-if="loading.mounted" />
  <div v-else class="dt-main-tabs-content">
    <!--dt-content-left可选-->
    <!-- <div class="dt-content-left">
      <PmComChatList />
    </div> -->
    <div class="progress-box" v-if="addLoading">
      <div class="inner">
        <el-progress type="circle" :percentage="percentage" :color="'rgba(47, 84, 235, 1)'"></el-progress>
        <div class="tip">批量添加数据中</div>
        <div class="num">请耐心等待... {{ finishedNum }}/{{ this.tableData.length }}</div>
      </div>
    </div>
    <div class="dt-content-main">
      <div class="dt-content-head">
        <div class="dt-content-head-tab">
          <div>
            <span class="dt-head-title">
              <!-- <i class="el-icon-arrow-left"></i>
              返回 -->
              批量导入
            </span>
            <em></em>
            <span class="dt-head-title">项目管理</span>
          </div>
        </div>
      </div>
      <div class="dt-content-page">
        <div class="dt-content-upload" v-if="!tableState" v-loading="loading" element-loading-text="文件上传中">
          <div class="dt-content-upload-in">
            <div class="dt-content-upload-in-left">
              <p>批量导入团队成员</p>
              <p>请先下载批量导入表格模版</p>
              <div>
                <el-button icon="el-icon-download" size="mini"> <a :href="fileUrl">下载模版</a> </el-button>
              </div>
            </div>
            <div class="dt-content-upload-in-right">
              <el-upload
                ref="uploadRef"
                class="upload-demo"
                drag
                action="#"
                :http-request="httpRequest"
                :show-file-list="false"
                :limit="1"
                :on-exceed="handleExceed"
              >
                <i class="el-icon-upload"></i>
                <div class="el-upload__text">将Excel文件拖到此处，或<em>点击上传</em></div>
                <!-- <div class="el-upload__tip" slot="tip">只能上传jpg/png文件，且不超过500kb</div> -->
              </el-upload>
            </div>
            <img class="dt-content-upload-in-bg1" src="/skb/img/bg-01.png" alt="" />
            <img class="dt-content-upload-in-bg2" src="/skb/img/bg-02.png" alt="" />
          </div>
        </div>
        <div class="top-tip" v-else>
          <div class="item">
            共提交 <span>{{ tableData.length }}</span> 人
          </div>
          <div class="item">
            成功 <span>{{ successNum }}</span> 人
          </div>
          <div class="item">
            失败 <span>{{ tableData.length - successNum }}</span> 人
          </div>
        </div>
        <div :class="tableState ? 'dt-content-upload-table finished' : 'dt-content-upload-table'" v-if="tableData.length">
          <div class="dt-content-upload-table-in">
            <el-table
              ref="tableRef"
              :data="tableData"
              border
              :height="tableHeight"
              style="width: 100%; color: #1f1f1f; font-size: 14px"
              :header-cell-style="headerRowStyle"
            >
              <el-table-column type="index" label="序号" width="80"> </el-table-column>
              <el-table-column prop="real_name" label="姓名" min-width="280"> </el-table-column>
              <el-table-column prop="id_card" label="身份证号" min-width="310"> </el-table-column>
              <el-table-column prop="phone" label="手机号" min-width="200"> </el-table-column>
              <el-table-column prop="speciality" label="专业" min-width="280">
                <template slot-scope="scope">
                  <span v-if="tableState">{{ scope.row.speciality }}</span>
                  <el-input size="mini" class="table-input" v-model="scope.row.speciality" placeholder="请输入专业" v-else></el-input>
                </template>
              </el-table-column>
              <el-table-column prop="title" label="职称" min-width="280">
                <template slot-scope="scope">
                  <span v-if="tableState">{{ scope.row.title }}</span>
                  <el-input size="mini" class="table-input" v-model="scope.row.title" placeholder="请输入职称" v-else></el-input>
                </template>
              </el-table-column>
              <el-table-column prop="result" label="结果" min-width="100" v-if="tableState">
                <template slot-scope="scope">
                  <span v-if="scope.row.result == '失败'" style="color: #f5222d">{{ scope.row.result }}</span>
                  <span v-else>{{ scope.row.result }}</span>
                </template>
              </el-table-column>
              <el-table-column prop="message" label="反馈" min-width="280" v-if="tableState">
                <template slot-scope="scope">
                  <span v-if="scope.row.result == '失败'" style="color: #f5222d">{{ scope.row.message }}</span>
                  <span v-else>{{ scope.row.message }}</span>
                </template>
              </el-table-column>
              <el-table-column prop="createTime" label="操作" min-width="280" v-if="!tableState">
                <template slot-scope="scope">
                  <el-button @click="handleClick(scope.$index)" type="text" size="small">删除</el-button>
                </template>
              </el-table-column>
            </el-table>
          </div>
        </div>
        <div class="dt-content-upload-table-btn" v-if="tableData.length">
          <el-button type="primary" size="small" class="btn" @click="addComfirm">{{ tableState ? '完成' : '确认添加' }}</el-button>
          <!-- <el-button size="small" class="dt-content-upload-table-btn-right">返回</el-button> -->
        </div>
      </div>
    </div>
  </div>
</template>
<script>
// /EnterpriseMember/enterprise_member_import  团队成员批量导入
// /EnterpriseMember/enterprise_member_batch_add  团队成员批量添加
export default {
  data() {
    return {
      Uid: this.$tools.getDecrypt(this.$store.state.uid), //用户id,
      finishedNum: 0,
      tableState: 0, // 0可修改
      loading: false,
      value: '',
      activeName: 'first',
      value1: '',
      input: '',
      url: '/EnterpriseMember/enterprise_member_import',
      tableData: [],
      addLoading: false,
      tableHeight: 400,
      secret_uid: this.$store.state.uid
    }
  },
  computed: {
    fileUrl() {
      return (
        'https://projectwebapi.ccccdt.com' +
        '/excel/template/团队成员模板.xlsx' +
        '?data=' +
        this.$tools.getZJSKAUTH(this.$store.state.uid, 'https://projectwebapi.ccccdt.com' + '/excel/template/团队成员模板.xlsx')
      )
    },
    successNum() {
      return this.tableData.filter((item) => item.result == '成功').length
    },
    percentage() {
      return parseInt((100 * this.finishedNum) / this.tableData.length)
    }
  },
  methods: {
    goDetail(id) {
      this.$router.push('/main/#/project/' + id)
    },
    handleClick(index) {
      this.tableData.splice(index, 1)
      this.getTableHeight()
    },
    showCard() {
      this.dataCard.isShowCard = true
    },
    headerRowStyle() {
      return {
        'font-size': '14px', // 设置表头字体大小
        'background-color': '#fafafa', // 设置表头背景色
        'font-weight': 'bold', // 设置表头字体加粗
        color: '#909399' // 设置表头字体颜色
      }
    },
    /* *************批量上传文件操作******************** */
    httpRequest(req) {
      this.$tools.getStsClient(this, req.file, (state, client, bucketName, file) => {
        if (state) {
          this.uploadFileAnnex(client, bucketName, file)
        }
      })
    },

    uploadFileAnnex(client, bucketName, file) {
      this.loading = true
      var time = new Date().getTime() + '',
        key = time.split('').reverse().join('') + this.$tools.getRandomName(file)
      var params = {
        Body: file,
        Bucket: bucketName,
        Key: key,
        ContentDisposition: `attachment; filename="${encodeURIComponent(file.name)}"`
      }
      client
        .putObject(params, (err, data) => {
          if (err) {
          } else {
            this.onSuccess(file, key)
          }
        })
        .on('httpUploadProgress', (progress) => {
          // this.onProgress(progress, file)
        })
    },
    onSuccess(file, key) {
      var data = [
          {
            file_url: 'https://www.ccccdt.com/ccccdt/' + key
          }
        ],
        domain = [this.$store.state.HOST],
        path = ['/EnterpriseMember/enterprise_member_import'],
        dataAxios = this.$tools.getDataAxios(this, domain, path, data)
      Promise.all(dataAxios)
        .then((response) => {
          this.$tools.callbackAxios(this, response, (response) => {
            this.$refs.uploadRef.clearFiles()
            var data = response[0].data
            console.log('onSuccess============', data)
            this.loading = false

            if (data.code === 200) {
              this.tableData = data.data.items
              this.getTableHeight()
            } else {
              this.$message.warning(data.message)
            }
          })
        })
        .catch((error) => {})
    },
    handleExceed(files, fileList) {
      this.$message.warning(`最多添加1个附件`)
    },
    /*************************** 文件上传结束***********************************************************/
    addComfirm() {
      if (this.tableState) {
        this.$router.push('/main/#/em?tab=list')
        //关闭导入tab
        this.$tools.setTabs(this, this.secret_uid, 'close', { hashName: 'em-import' })
      } else {
        this.$confirm(`确定添加${this.tableData.length}名成员吗？`, '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          cancelButtonClass: 'dt-button-cancle is-plain',
          // iconClass: '',
          type: 'warning',
          customClass: 'dt-chat-content-link-confirm'
        })
          .then(() => {
            this.addLoading = true
            var data = [
                {
                  user_id: this.Uid,
                  batch_member_json: JSON.stringify(this.tableData)
                }
              ],
              domain = [this.$store.state.HOST],
              path = ['/EnterpriseMember/enterprise_member_batch_add'],
              dataAxios = this.$tools.getDataAxios(this, domain, path, data)
            Promise.all(dataAxios)
              .then((response) => {
                this.$tools.callbackAxios(this, response, (response) => {
                  this.$refs.uploadRef.clearFiles()
                  var data = response[0].data
                  console.log('addComfirm============', data)

                  if (data.code === 200) {
                    let num = this.tableData.length
                    let gap = num < 100 ? parseInt(2000 / num) : 20
                    let finishInterval = setInterval(() => {
                      if (this.finishedNum == num) {
                        clearInterval(finishInterval)
                        this.addLoading = false
                        this.tableData = data.data
                        this.tableState = 1
                        this.getTableHeight()
                      } else ++this.finishedNum
                    }, gap)
                  } else {
                  }
                })
              })
              .catch((error) => {})
          })
          .catch((error) => {})
      }
    },
    getTableHeight() {
      this.tableHeight = 0
      var th = 0
      if (this.tableData.length) th = 40 * this.tableData.length + 41
      this.$nextTick(() => {
        setTimeout(() => {
          if (!this.tableData.length) return
          const contentHeight = document.querySelector('.dt-content-upload-table-in').clientHeight
          const headerHeight = document.querySelector('.dt-content-upload-table-in .el-table__header-wrapper').clientHeight
          var ttHeight = contentHeight - headerHeight
          if (th < ttHeight && th > 0) this.tableHeight = th
          else this.tableHeight = ttHeight

          this.$refs.tableRef.doLayout()
        }, 100)
      })
    }
  },

  mounted() {
    window.addEventListener('resize', this.getTableHeight)

    document.body.ondrop = function (event) {
      console.log('dragover=============')
      event.preventDefault() // 阻止默认行为
      event.stopPropagation() // 阻止事件冒泡
    }
  },
  beforeDestroy() {
    window.removeEventListener('resize', this.getTableHeight)
  }
}
</script>
<style scoped>
.dt-content-page {
  margin: 0;
  background-color: #f2f3f5;
  padding: 16px;
}
.dt-content-head-tab em {
  height: 16px;
  width: 1px;
  display: inline-block;
  background-color: #e9eef7;
  margin: 0 16px;
}
.dt-content-upload {
  padding: 14px;
  background-color: #fff;
}
.dt-content-upload-in {
  height: 212px;
  background-color: #f0f5ff;
  display: flex;
  padding: 14px 14px 14px 0;
  align-items: center;
  position: relative;
  box-sizing: border-box;
}
.dt-content-upload-in-left {
  width: 592px;
  text-align: left;
  padding-left: 200px;
  box-sizing: border-box;
}

.dt-content-upload-in-left .el-button--mini {
  height: 32px;
  color: #1f1f1f;
}
.dt-content-upload-in-right {
  /* width: 1184px; */
  flex-grow: 1;
  height: 184px;
  /* border: 2px dashed #e9eef7; */
  box-sizing: border-box;
  /* border-radius: 8px; */
  /* background-color: #fff; */
  /* opacity: 0.6; */
}
.dt-content-upload-in-left p:nth-of-type(1) {
  font-size: 20px;
  line-height: 26px;
  color: #1f1f1f;
  font-weight: bold;
  margin-bottom: 10px;
}
.dt-content-upload-in-left p:nth-of-type(2) {
  font-size: 14px;
  color: #909399;
  line-height: 18px;
  margin-bottom: 24px;
}
.dt-content-upload-in-bg1 {
  position: absolute;
  left: 0;
  bottom: 0;
}
.dt-content-upload-in-bg2 {
  position: absolute;
  left: 473px;
  bottom: 0;
}
.dt-content-upload-in-right .upload-demo {
  width: 100%;
}
.dt-content-upload-in-right .upload-demo >>> .el-upload {
  width: 100%;
}
.dt-content-upload-in-right .upload-demo >>> .el-upload .el-upload-dragger {
  width: 100%;
  opacity: 0.6;
}

.dt-content-upload-in-right .upload-demo >>> .el-upload .el-upload-dragger.is-dragover {
  background-color: #fff;
  opacity: 1;
}
.dt-content-upload-table {
  background-color: #fff;
  border-bottom: 1px solid #e9eef7;
  height: calc(100% - 305px);
}
.finished {
  height: calc(100% - 100px);
  padding-top: 14px;
}

.dt-content-upload-table-in {
  padding: 14px;
  height: 100%;
  padding-top: 0;
}

/* 全局样式中设置行高 */
.dt-content-upload-table-in >>> .el-table .el-table__row {
  height: 40px;
}
.dt-content-upload-table-in >>> .el-table th.el-table__cell {
  padding: 0;
  height: 40px;
  color: '#909399';
}
.dt-content-upload-table-in >>> .el-table .el-table__cell {
  padding: 0;
  color: #1f1f1f;
}

.dt-content-upload-table-in >>> .el-button--small {
  font-size: 14px !important;
}
.table-input {
  color: #1f1f1f !important;
}

.dt-content-upload-table-btn {
  background-color: #fff;
  padding: 12px;
  text-align: center;
}
.dt-content-upload-table-btn .btn {
  width: 116px;
  height: 36px;
  padding: 0;
}
.dt-content-upload-table-btn-right {
  margin-left: 12px;
  width: 146px;
}
.dt-main-tabs-content {
  position: relative;
}
.progress-box {
  position: absolute;
  left: 0;
  right: 0;
  top: 0;
  bottom: 0;
  background: rgba(255, 255, 255, 0.8);
  z-index: 10;
  display: flex;
  justify-content: center;
  align-items: center;
}

.progress-box .inner {
  display: flex;
  flex-direction: column;
}

.progress-box .inner .tip {
  font-family: Microsoft YaHei;
  color: #1f1f1f;
  font-size: 18px;
  text-align: center;
  margin: 30px auto 10px;
}

.progress-box .inner .num {
  font-family: Microsoft YaHei;
  color: #2f54eb;
  font-size: 14px;
  text-align: center;
}
.top-tip {
  display: flex;
  padding-bottom: 16px;
}
.top-tip .item {
  font-family: Microsoft YaHei;
  color: #1f1f1f;
  font-size: 14px;
  margin-right: 42px;
}

.top-tip .item span {
  font-weight: bold;
  padding: 0 4px;
}

/* 滚动条轨道样式 */
::v-deep .dt-content-upload-table-in .el-table__body-wrapper::-webkit-scrollbar {
  width: 6px; /* 设置滚动条宽度 */
}

/* 滚动条滑块样式 */
::v-deep .dt-content-upload-table-in .el-table__body-wrapper::-webkit-scrollbar-thumb {
  background-color: #cccccc; /* 设置滑块背景颜色 */
  border-radius: 2px; /* 设置滑块圆角 */
}

/* 滚动条轨道hover状态样式 */
::v-deep .dt-content-upload-table-in .el-table__body-wrapper::-webkit-scrollbar-track:hover {
  background-color: #f1f1f1; /* 设置轨道hover状态时的背景颜色 */
}

/* 滚动条滑块hover状态样式 */
::v-deep .dt-content-upload-table-in .el-table__body-wrapper::-webkit-scrollbar-thumb:hover {
  background-color: #888; /* 设置滑块hover状态时的背景颜色 */
}
</style>
